package com.netted.myapplication;

import android.Manifest;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;
import io.agora.rtc.video.VideoCanvas;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    private static final String LOG_TAG = MainActivity.class.getSimpleName();
    TalkLeftAdapter adapter = null;
    private TextView exitTV;
    private WebSocketClient mSocketClient;
    private Button sendBtn;
    private EditText sendET;
    String userId = "201";
    String userName = "li";
    private String userInfo = this.userId + "/168/" + this.userName + "/U/123.PNG";


    private Handler handler = new Handler() {
        public void handleMessage(Message paramAnonymousMessage) {
            MainActivity.this.adapter.notifyDataSetChanged();
        }
    };
    List<Map<String, String>> list = new ArrayList();
    private ListView listView;
    private RtcEngine mRtcEngine;

    @Override
    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        setContentView(R.layout.activity_main);
        initView();
        if ((checkSelfPermission("android.permission.RECORD_AUDIO", 22)) && (checkSelfPermission("android.permission.CAMERA", 23))) {
            initAgoraEngineAndJoinChannel();
        }
        initScoket();
    }

    private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() {
        public void onFirstRemoteVideoDecoded(final int paramAnonymousInt1, int paramAnonymousInt2, int paramAnonymousInt3, int paramAnonymousInt4) {
            runOnUiThread(new Runnable() {
                public void run() {
                    setupRemoteVideo(paramAnonymousInt1);
                }
            });
        }

        public void onUserMuteVideo(final int paramAnonymousInt, final boolean paramAnonymousBoolean) {
            runOnUiThread(new Runnable() {
                public void run() {
                    onRemoteUserVideoMuted(paramAnonymousInt, paramAnonymousBoolean);
                }
            });
        }

        public void onUserOffline(int paramAnonymousInt1, int paramAnonymousInt2) {
            runOnUiThread(new Runnable() {
                public void run() {
                    onRemoteUserLeft();
                }
            });
        }
    };


    private void initAgoraEngineAndJoinChannel() {
        initializeAgoraEngine();
        setupVideoProfile();
        setupLocalVideo();
        joinChannel();
    }

    private void initScoket() {
        try {
            String str = "wss://teaching.dezhi.com.au/WSServer/" + MainActivity.this.userInfo;
            mSocketClient = new WebSocketClient(new URI(str)) {
                public void onClose(int paramAnonymous2Int, String paramAnonymous2String, boolean paramAnonymous2Boolean) {
                    Log.d("picher_log", "通道关闭");
                }

                public void onError(Exception paramAnonymous2Exception) {
                    Log.d("picher_log", "链接错误");
                }

                public void onMessage(String paramAnonymous2String) {
                    Log.d("loadmsg", "@#################" + paramAnonymous2String);
                    MainActivity.this.loadMessage(paramAnonymous2String);
                }

                public void onOpen(ServerHandshake paramAnonymous2ServerHandshake) {
                }
            };
            mSocketClient.connect();
            return;
        } catch (URISyntaxException localURISyntaxException) {
            localURISyntaxException.printStackTrace();
        }
        sendBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View paramAnonymousView) {
                String str;
                if (MainActivity.this.mSocketClient != null) {
                    str = MainActivity.this.sendET.getText().toString();
                    if ((str != null) && (!str.replaceAll(" ", "").equals(""))) {
                    }
                } else {
                    return;
                }
                try {
                    JSONObject localJSONObject = new JSONObject();
                    localJSONObject.put("message", str.toString());
                    localJSONObject.put("sendUserId", MainActivity.this.userId);
                    localJSONObject.put("userName", "wang");
                    localJSONObject.put("courseId", "168");
                    localJSONObject.put("userPic", "123.png");
                    localJSONObject.put("order", "chat");
                    mSocketClient.send(localJSONObject.toString());
                    sendET.setText("");
                    return;
                } catch (JSONException localJSONException) {
                    localJSONException.printStackTrace();
                    Toast.makeText(MainActivity.this, localJSONException.getMessage(), Toast.LENGTH_LONG).show();
                    Log.e("###################eee", localJSONException.getMessage());
                }
            }
        });
    }

    private void initView() {
        this.sendBtn = ((Button) findViewById(R.id.send_btn));
        this.sendET = ((EditText) findViewById(R.id.send_et));
//        this.exitTV = ((TextView)findViewById(2131230791));
        this.listView = ((ListView) findViewById(R.id.list_view));
        this.list = new ArrayList();
        this.adapter = new TalkLeftAdapter(this.list, this);
        this.listView.setAdapter(this.adapter);
    }

    private void initializeAgoraEngine() {
        try {
            this.mRtcEngine = RtcEngine.create(getBaseContext(), "bffcf6396ea547a7987df2739d87c4b4", this.mRtcEventHandler);
            return;
        } catch (Exception localException) {
            Log.e(LOG_TAG, Log.getStackTraceString(localException));
            throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(localException));
        }
    }

    private void joinChannel() {
        this.mRtcEngine.joinChannel(null, "168", "Extra Optional Data", 0);
    }

    private void leaveChannel() {
        this.mRtcEngine.leaveChannel();
    }

    private void onRemoteUserLeft() {
        ((FrameLayout) findViewById(R.id.remote_video_view_container)).removeAllViews();
    }

    private void onRemoteUserVideoMuted(int paramInt, boolean paramBoolean) {
        SurfaceView localSurfaceView = (SurfaceView) ((FrameLayout) findViewById(R.id.remote_video_view_container)).getChildAt(0);
        Object localObject = localSurfaceView.getTag();
        if ((localObject != null) && (((Integer) localObject).intValue() == paramInt)) {
            int i = 0;
            if (paramBoolean) {
                i = 8;
            }
            localSurfaceView.setVisibility(i);
        }
    }

    private void setupLocalVideo() {
        FrameLayout localFrameLayout = (FrameLayout) findViewById(R.id.local_video_view_container);
        SurfaceView localSurfaceView = RtcEngine.CreateRendererView(getBaseContext());
        localSurfaceView.setZOrderMediaOverlay(true);
        localFrameLayout.addView(localSurfaceView);
        this.mRtcEngine.setupLocalVideo(new VideoCanvas(localSurfaceView, 3, 0));
    }

    private void setupRemoteVideo(int paramInt) {
        FrameLayout localFrameLayout = (FrameLayout) findViewById(R.id.local_video_view_container);
        if (localFrameLayout.getChildCount() >= 1) {
            return;
        }
        SurfaceView localSurfaceView = RtcEngine.CreateRendererView(getBaseContext());
        localFrameLayout.addView(localSurfaceView);
        this.mRtcEngine.setupRemoteVideo(new VideoCanvas(localSurfaceView, 3, paramInt));
        localSurfaceView.setTag(Integer.valueOf(paramInt));
    }

    private void setupVideoProfile() {
        this.mRtcEngine.enableVideo();
        this.mRtcEngine.setVideoProfile(30, false);
    }

    public boolean checkSelfPermission(String paramString, int paramInt) {
        Log.i(LOG_TAG, "checkSelfPermission " + paramString + " " + paramInt);
        if (ContextCompat.checkSelfPermission(this, paramString) != 0) {
            ActivityCompat.requestPermissions(this, new String[]{paramString}, paramInt);
            return false;
        }
        return true;
    }

    public void loadMessage(String paramString) {
        if ((paramString == null) || ("".equals(paramString))) {
            return;
        }
        for (; ; ) {
            String str1;
            String str3;
            try {
                JSONObject localJSONObject = new JSONObject(paramString);
                if (!"chat".equals(localJSONObject.get("order") + "")) {
                    break;
                }
                str1 = localJSONObject.get("sendUserId") + "";
                String str2 = localJSONObject.get("message") + "";
                str3 = localJSONObject.get("userName") + "";
                HashMap localHashMap = new HashMap();
                localHashMap.put("sendUserId", str1);
                localHashMap.put("message", str2);
                if (str1.equals("200")) {
                    str3 = "王莹";
                    localHashMap.put("userName", str3);
                    localHashMap.put("userId", this.userId);
                    this.list.add(localHashMap);
                    new Thread() {
                        public void run() {
                            MainActivity.this.handler.sendEmptyMessage(0);
                        }
                    }.start();
                    return;
                }
            } catch (Exception localException) {
                localException.printStackTrace();
                return;
            }
            if (str1.equals("201")) {
                str3 = "陈泽";
            } else if (str1.equals("202")) {
                str3 = "陆子涵";
            } else if (str1.equals("203")) {
                str3 = "吴择达";
            } else if (str1.equals("204")) {
                str3 = "张丹露";
            }
        }
    }


    protected void onDestroy() {
        super.onDestroy();
        leaveChannel();
        RtcEngine.destroy();
        this.mRtcEngine = null;
    }

    public void onEncCallClicked(View paramView) {
        finish();
    }

    public void onLocalAudioMuteClicked(View paramView) {
        ImageView localImageView = (ImageView) paramView;
        if (localImageView.isSelected()) {
            localImageView.setSelected(false);
            localImageView.clearColorFilter();
        }
        /*for (;;)
        {
            this.mRtcEngine.muteLocalAudioStream(localImageView.isSelected());
            return;
            localImageView.setSelected(true);
            localImageView.setColorFilter(getResources().getColor(2131034151), PorterDuff.Mode.MULTIPLY);
        }*/
    }

    public void onLocalVideoMuteClicked(View paramView) {
        ImageView iv = (ImageView) paramView;
        if (iv.isSelected()) {
            iv.setSelected(false);
            iv.clearColorFilter();
        } else {
            iv.setSelected(true);
            iv.setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.MULTIPLY);
        }

        mRtcEngine.muteLocalVideoStream(iv.isSelected());

        FrameLayout container = (FrameLayout) findViewById(R.id.local_video_view_container);
        SurfaceView surfaceView = (SurfaceView) container.getChildAt(0);
        surfaceView.setZOrderMediaOverlay(!iv.isSelected());
        surfaceView.setVisibility(iv.isSelected() ? View.GONE : View.VISIBLE);
    }

    private static final int PERMISSION_REQ_ID_RECORD_AUDIO = 22;
    private static final int PERMISSION_REQ_ID_CAMERA = PERMISSION_REQ_ID_RECORD_AUDIO + 1;

    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[], @NonNull int[] grantResults) {
        Log.i(LOG_TAG, "onRequestPermissionsResult " + grantResults[0] + " " + requestCode);

        switch (requestCode) {
            case PERMISSION_REQ_ID_RECORD_AUDIO: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    checkSelfPermission(Manifest.permission.CAMERA, PERMISSION_REQ_ID_CAMERA);
                } else {
                    showLongToast("No permission for " + Manifest.permission.RECORD_AUDIO);
                    finish();
                }
                break;
            }
            case PERMISSION_REQ_ID_CAMERA: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initAgoraEngineAndJoinChannel();
                } else {
                    showLongToast("No permission for " + Manifest.permission.CAMERA);
                    finish();
                }
                break;
            }
        }
    }

    public void onSwitchCameraClicked(View paramView) {
        this.mRtcEngine.switchCamera();
    }

    public final void showLongToast(final String paramString) {
        runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(MainActivity.this.getApplicationContext(), paramString, Toast.LENGTH_LONG).show();
            }
        });
    }
}
